//
//  UserAccount.swift
//  新浪微播
//
//  Created by lxw on 15/12/17.
//  Copyright © 2015年 lxw. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding{
    
    var access_token: String?
    var expires_in: NSTimeInterval = 0{
        didSet{
            expires_date = NSDate (timeIntervalSinceNow: expires_in)
        }
    }
    var expires_date: NSDate?
    var uid: String?
    var name: String?
    var avatar_large: String?
    
    //KVC 给对象设置初始值
    init(dict: [String : AnyObject]) {
        //对象构造的最后一步
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    func saveAccount(){
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        print(path)
        //保存自定义对象
        NSKeyedArchiver . archiveRootObject(self, toFile: path)
    }
    
    class func loadAccount() -> UserAccount?{
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!  as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
           
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }

            
        }
        return nil
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder . decodeObjectForKey("access.token") as? String
        
         expires_in = aDecoder . decodeDoubleForKey("expires_in")
        
         uid = aDecoder . decodeObjectForKey("uid") as? String
        
         avatar_large = aDecoder . decodeObjectForKey("avatar_large") as? String
        
         name = aDecoder . decodeObjectForKey("name") as? String
        
        expires_date = aDecoder . decodeObjectForKey("expires_date") as? NSDate 
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
}














